﻿#ifndef _CELL_NETWORK_HPP_
#define _CELL_NETWORK_HPP_

#include "CELL.h"

class CELLNetWork
{
public:
	~CELLNetWork()
	{
#ifdef _WIN32
		WSACleanup();
#endif
	}

	static void Init()
	{
		static CELLNetWork obj;
	}

	static int make_reuseaddr(SOCKET fd)
	{
		// 设置端口可复用
		int flag = 1;
		if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&flag, sizeof(flag)))
		{
			CELLLog_Info("setsockopt SO_REUSEADDR fail");
			return SOCKET_ERROR;
		}
		return 0;
	}

	static int destorySocket(SOCKET fd)
	{
#ifdef _WIN32
		int ret = closesocket(fd);
#else
		int ret = close(fd);
#endif
		if (ret < 0)
		{
			CELLLog_pError("destory sockfd<%d>", (int)fd);
		}
		return ret;
	}
private:
	CELLNetWork()
	{
#ifdef _WIN32
		WORD ver = MAKEWORD(2, 2);
		WSADATA dat;
		WSAStartup(ver, &dat);
#endif
		// unix系统在客户端退出时会产生管道信号导致程序退出，此处忽略
#ifndef _WIN32
		if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
			return;
#endif
	}
};

#endif // #ifndef _CELL_NETWORK_HPP_